// pages/activedetial/activedetial.js
var WxParse = require("../../wxParse/wxParse.js");
var api = require("../../api.js"),
  time = null,
  app = getApp();
var r, tips, act_id;
var bmap = require('../../asset/plugins/bmap-wx.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    istrue: false,
    currentIndex: 0,
    detial_activity: {},
    price: "", // 实付款
    partner: {},
    enrolls: [],
    consultes: [],
    active_title: "",
    showModalStatus: false, //是否显示
    gg_price: 0, //规格价格
    type: [],
    num: 1, //初始数量
    onFocus: false, //textarea焦点是否选中
    isShowText: false, //控制显示 textarea 还是 text
    remark: "",
    selectPerson: true,
    saveMoney: '请选择优惠卷',
    selectArea: false,
    end: 0,
    replyUserName: "",
    replayarr: [],
    pageIndex: 2,
    popup: true,
    loadMoreJson: false,
    loadMore: false,
    vipPrice: "",
    onlyPeople: 0,
    hidden: true,
    popup1: true,
    asId: '',
    assible: true,
    pink: false,
    time: null,
    checkAssemble: false,
    showShare: true, // 顶部的邀请显示 （true 不显示）
    inviteOpenId: '',
    inviteType: null,
    on: true, // 控制音乐的状态，以及图标是否旋转
    is_vip: 0 // 是否为 VIP 会员 0 否 1 是
  },

  // 放在onReady函数中，使在进入页面后，音乐就自动开始
  // onReady() {
  //   // 获取BackgroundAudioManager 实例
  //   this.back = wx.getBackgroundAudioManager()
  //   // 对实例进行设置
  //   this.back.src = "https://qiniu.v2too.com/%E8%B5%B5%E9%9B%B7%20-%20%E6%88%90%E9%83%BD.mp3"
  //   this.back.title = 'Tassel' // 标题为必选项
  //   this.back.play() // 开始播放
  // },
  // 播放或暂停音乐
  stop_music() {
    this.back.pause(); // 点击音乐图标后出发的操作
    this.setData({
      on: !this.data.on
    })
    if (this.data.on) {
      this.back.play()
    } else {
      this.back.pause()
    }
  },
  /**生命周期函数--监听页面加载*/
  onLoad: function(options) {
    r = this;
    act_id = options.id;
    /** 检测是否授权 */
    getApp().is_empower();
    /** 邀请人不为空的时候触发 */
    if (options.inviteOpenId) {
      r.setData({
        inviteOpenId: options.inviteOpenId,
        inviteType: options.inviteType
      })
      if (options.inviteType != 1 && options.inviteType != null) { /** 拼团 和 邀请*/
        /** inviteType == 2 参与拼团 */
        r.setData({
          checkAssemble: true,
        });
      }
    };
    r.setData({
      id: options.id,
    });
  },
  onShow: function() {
    var that = this;
    if (app.globalData.time) {
      clearTimeout(app.globalData.time);
    };
    /** 初始化数据 */
    r.init();
    r.toast = that.selectComponent("#toast");
    tips = that.selectComponent("#mytips");
  },

  //初始化数据
  init() {
    /** 延迟 1s 触发  方便获取 open_id */
    setTimeout(() => {
      var that = this;
      var open_id = getApp().globalData.open_id;
      var userid = open_id;
      console.log('邀请类型 -- >' + that.data.inviteType)
      if (that.data.inviteType == 1) { /** 拼团 和 邀请*/
        const t = new Object();
        t.inviteOpenId = that.data.inviteOpenId,
          t.openId = open_id;
        t.actId = that.data.id
        app.getData.shareAct(t).then(res => {
          r.setData({
            invite_img: res.data.invite_img,
            invite_name: res.data.invite_name,
            showShare: false,
          });
        })
      }
      const first = new Promise((resolve, reject) => {
        var typeStatus = ['未开始', '进行中', '已结束', '已报名', '拼团中', '拼团成功', '拼团失败'];
        var _that = this;
        var n = new Object();
        n.openId = open_id;
        n.activityId = _that.data.id;
        that.data.inviteOpenId ? n.inviteOpenId = that.data.inviteOpenId : '';
        wx.request({
          url: api.detail.actDetail,
          data: n,
          success: function(res) {
            if (res.statusCode == 200) {
              if (res.data.code == 200) {
                var t = res.data.data;
                console.log(t)
                var onlyPeople = Number(t.activityMaxperson) - Number(t.activitySurplusperson);
                var statusType = t.activityStatus;
                if (t.activityStatus != 0 && t.activityStatus != 1) {
                  if (t.activityStatus == 3 || t.activityStatus == 4 || t.activityStatus == 5) {
                    statusType = 1;
                  } else {
                    statusType = 2
                  }
                }
                /** 拼团已满 */
                if (t.able_assemble == 1) {
                  /** 弹出提示框 */
                  wx.showToast({
                    title: '拼团已满',
                    image: '../../images/error_yellow.png',
                    duration: 3000
                  })
                }
                /** 拼团成功和拼团失败都不弹出拼团的弹窗 */
                if (_that.data.checkAssemble && t.activityStatus != 5 && t.able_assemble != 1) {
                  _that.setData({
                    assible: false,
                    /** 显示拼团的弹出 */
                    pink: true,
                  });
                  /** 倒计时定时器 */
                  _that.countDown();
                }
                if (t.activityDescription) {
                  // WxParse.wxParse("activityDescription","html",t.activityDescription, _that, 5);
                  const img = t.activityDescription;
                  t.activityDescription = img.replace(/\<img/gi, '<img style="max-width:100%;height:auto;" ')
                }
                /** 参与拼团 */
                if (_that.inviteOpenId && r.data.inviteType == 2) {
                  _that.setData({
                    invite_img: t.invite_img,
                    invite_name: t.invite_name,
                  });
                }
                _that.setData({
                  detial_activity: t,
                  node1: t.activityDescription,
                  onlyPeople: onlyPeople,
                  statusType: statusType,
                  typeStatus: typeStatus,
                  openid: open_id,
                  isCollection: t.isCollection,
                  is_vip: t.is_vip /** 是否为 vip  */
                });
                resolve(res);
              }
            }
          }
        });
      });
      first.then((res) => {
        console.log('详情中的 open_id -- > ' + getApp().globalData.open_id)
        Promise.all([that.getPartner(), that.getEnrolls(), that.getConsultData()]).then(data => {
          setTimeout(() => {
            this.setData({
              hidden: false,
              userid: userid,
            })
          }, 500);
        });
      }, function(err) {
        console.log(err)
      })
    }, 1000);
  },
  //获取活动人员的信息
  getPartner() {
    var _that = this;
    const p = new Promise((resolve, reject) => {
      wx.request({
        url: api.art.partner,
        data: {
          id: _that.data.detial_activity.activityCreatepartner
        },
        success: function(res) {
          if (res.statusCode == 200) {
            if (res.data.code == 200) {
              var t = res.data.data;
              if (t) {
                const img = t.partnerDesc;
                //t.partnerDesc = img.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
                _that.setData({
                  partner: t
                });
                // if(t.partnerDesc){
                //   WxParse.wxParse("article","html",t.partnerDesc,_that,5); 
                // };
              }
              resolve(res)
            }
          }

        }
      });
    })
    return p;
  },
  // 报名人员
  getEnrolls() {
    var _that = this;
    const p = new Promise((resolve, reject) => {
      var n = new Object();
      n = {
        pageIndex: 1,
        pageSize: 10,
        otherId: _that.data.detial_activity.activityUUID,
        ordType: 2
      }
      wx.request({
        url: api.audio.enrolls,
        data: n,
        success: function(res) {
          if (res.statusCode == 200) {
            if (res.data.code == 200) {
              var arr = [];
              var t = res.data.data;
              if (t) {
                t.length > 6 ? arr = t.slice(0, 6) : arr = t
              } else {
                arr = [];
              }
              _that.setData({
                enrolls: arr
              });
              resolve(res);
            }
          }
        }
      });
    })
    return p;

  },
  // 获取评论列表
  getConsultData() {
    var _that = this;
    const p = new Promise((resolve, reject) => {
      var n = new Object();
      var replayarr = [];
      n = {
        pageIndex: 1,
        pageSize: 5,
        otherId: _that.data.id
      }
      wx.request({
        url: api.detail.consultData,
        data: n,
        success: function(res) {
          if (res.statusCode == 200) {
            if (res.data.code == 200) {
              var t = res.data.data;
              if (t.length > 0) {
                _that.setData({
                  consultes: t,
                  loadMoreJson: true,
                  loadMore: true
                });
              } else {
                _that.setData({
                  consultes: [],
                  loadMoreJson: false,
                  loadMore: false
                });
              };
              resolve(res)
            }

          }
        }
      });
    });
    return p;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading(),
      console.log("下拉刷新")
    r.init();
    r.setData({
      checkAssemble: false
    });
    setTimeout(function() {
      wx.hideNavigationBarLoading(), wx.stopPullDownRefresh();
    }, 1500);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var openid = getApp().globalData.wxUserInfo.openId;
    //  if (res.from === 'button') {
    // console.log(12312)
    return {
      title: r.data.detial_activity.activityTitle,
      path: `pages/index/index?id=${r.data.detial_activity.activityId}&shareType=0&inviteType=1&inviteOpenId=${openid}`,
      success: function(res) {},
      fail: function(res) {}
    }
    //  }
  },
  accSub: function(arg1, arg2) {
    var r1, r2, m, n;
    try {
      r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
  //点击购买
  submitForm(e) {
    var form = e.detail.value;
    var that = this;
    var t = new Object();
    var user = getApp().globalData.wxUserInfo;
    console.log('open_id ---- > ' + getApp().globalData.wxUserInfo.openId)
    t = {
      body: "活动购买",
      ordType: "2",
      userBusiness: form.userBusiness,
      userJob: form.userJob,
      userName: form.userName,
      userPhone: form.userPhone,
      userRemark: form.userRemark,
      openId: getApp().globalData.wxUserInfo.openId,
      otherId: that.data.detial_activity.activityUUID,
      ordMoney: that.data.price,
      isAssemble: that.data.isAssemble
    };
    that.data.mcId ? t.mcId = that.data.mcId : '';
    if (that.data.pink) {
      t.specId = that.data.detial_activity.assemble.specId;
      t.assembleId = that.data.detial_activity.assemble.asId;
    }
    if (t.userName == null || t.userName == "") {
      tips.showTopTip('姓名不能为空');
      return;
    }
    if (t.userPhone == null || t.userPhone == "") {
      tips.showTopTip('手机号为空');
      return;
    } else {
      if (!/^1[34578]\d{9}$/.test(e.detail.value.userPhone)) {
        tips.showTopTip('手机号格式错误');
        return false;
      }
    }
    if (t.userBusiness == null || t.userBusiness == "") {
      tips.showTopTip('企业不能为空');
      return;
    }
    if (t.userJob == null || t.userJob == "") {
      tips.showTopTip('职位不能为空');
      return;
    }
    wx.request({
      url: api.pay.toBuy,
      data: t,
      success: function(res) {
        console.log(res);
        console.log('res.data.code -- > ' + res.data.code)
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            var data = res.data.data;
            if (t.ordMoney != 0) {
              wx.requestPayment({
                timeStamp: data.timeStamp.toString(),
                nonceStr: data.nonceStr,
                package: data.package,
                signType: "MD5",
                paySign: data.paySign,
                success: function(res) {
                  console.log("支付成功");
                },
                fail: function(res) {
                  console.log("支付失败");
                  return;
                },
                complete: function(res) {
                  console.log("支付完成");
                  if (res.errMsg == "requestPayment:ok") {
                    wx.showToast({
                      title: "支付成功",
                      icon: "success"
                    });
                    setTimeout(() => {
                      if (that.data.isAssemble == 0) {
                        that.init();
                        r.setData({
                          checkAssemble: false
                        });
                        that.hideModal();
                      } else {
                        that.hideModal();
                        if (that.data.inviteOpenId) {
                          that.init();
                          r.setData({
                            checkAssemble: false
                          });
                        } else {
                          wx.navigateTo({
                            url: "../../pages/assemble/assemble?actUUID=" + that.data.detial_activity.activityUUID
                          });
                        }
                      }
                    }, 1500);
                  }
                  return;
                }
              });
            } else {
              that.hideModal();
              setTimeout(() => {
                wx.showToast({
                  title: '报名成功',
                  image: '../../images/bm_ok_01.png',
                  duration: 2000
                }), 800
              });
              setTimeout(() => {
                if (that.data.isAssemble == 0) {
                  that.init();
                } else {
                  if (that.data.inviteOpenId) {
                    that.init();
                  } else {
                    wx.navigateTo({
                      url: "../../pages/assemble/assemble?actUUID=" + that.data.detial_activity.activityUUID
                    });
                  }
                }
              }, 1000);
            }
          } else {
            wx.showToast({
              title: "购买失败",
            });
          }
        }
      }
    });
  },
  //提交评论
  replaySubmit: function(e) {
    var form = e.detail.value;
    var that = this;
    var user = getApp().globalData.wxUserInfo;
    var t = new Object();
    let conArea = form.conArea;
    if (conArea == "") {
      wx.showToast({
        title: "内容为空"
      });
      return false;
    }
    (t.openId = user.openId),
    (t.otherId = that.data.detial_activity.activityId),
    (t.conArea = conArea),
    (t.type = 0);
    wx.request({
      url: api.detail.addConsult,
      data: t,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        // console.log(res);
        if (res.statusCode == 200 && res.data.code == 200) {
          wx.showToast({
            title: "评论成功"
          });
          that.setData({
            popup: true
          });
          // 获取评论列表
          var t = new Object();
          var replayarr = [];
          (t.pageIndex = "1"), (t.pageSize = "3"), (t.otherId = that.data.id);
          wx.request({
            url: api.detail.consultData,
            data: t,
            success: function(res) {
              if (res.statusCode == 200 && res.data.code == 200) {
                if (res.data.data.length > 0) {
                  that.setData({
                    consultes: res.data.data,
                    loadMoreJson: true
                    // replayarr: replayarr
                  });
                  // console.log(that.data);
                } else {
                  that.setData({
                    consultes: res.data.data
                  });
                }
              }
            }
          });
        } else {
          wx.showToast({
            title: res.data.msg
          });
        }
      }
    });
  },
  // 下拉加载咨询
  loadMore: function() {
    var t = new Object();
    var that = this;
    var replayarr = [];
    t.pageIndex = that.data.pageIndex;
    t.pageSize = "3";
    t.otherId = that.data.id;
    if (!that.data.loadMoreJson) {
      return;
    }
    wx.request({
      url: api.detail.consultData,
      data: t,
      success: function(res) {
        if (res.statusCode == 200 && res.data.code == 200) {
          if (res.data.data.length > 0) {
            that.data.pageIndex++;
            that.setData({
              loadMoreJson: true,
              consultes: that.data.consultes.concat(res.data.data)
            });
            // console.log(that.data);
          } else {
            that.setData({
              loadMoreJson: false
            });
          }
        }
      }
    });
  },
  //测试跳转人员列表
  userlist: function(e) {
    // console.log(e.currentTarget.dataset);
    wx.navigateTo({
      url: "../userlist/userlist?id=" + e.currentTarget.dataset.id + "&type=2"
    });
  },
  //选择场次 
  filter: function(e) {
    // console.log(e);
    var that = this;
    var details = e.currentTarget.dataset.detail;
    var price = that.data.isAssemble == 1 ? details.assemblePrice : (details.specVIPprice ? details.specVIPprice : details.specPrice);
    this.setData({
      currentIndex: e.currentTarget.dataset.current,
      price: price,
      gg_price: that.data.isAssemble == 1 ? details.assemblePrice : (details.specVIPprice ? details.specVIPprice : details.specPrice)
    });
  },
  //显示对话框
  showModal: function(e) {
    /** 是否授权 */
    var that = this;
    var res = that.is_authorize();
    if (res == 0) return
    /** 是否拼团 1 是 0 否 */
    var isassemble = e.currentTarget.dataset.isassemble;
    console.log('是否拼团 1 是 0 否 -->  ' + isassemble)
    that.setData({
      isAssemble: isassemble
    });
    /** 活动规格获取 */
    wx.request({
      url: api.detail.actSpecByUUID + "/" + that.data.detial_activity.activityUUID,
      success: function(res) {

        if (res.data.length > 0) {
          var price = isassemble == 1 ? res.data[0].assemblePrice : (res.data[0].specVIPprice ? res.data[0].specVIPprice : res.data[0].specPrice);
          that.setData({
            type: res.data,
            gg_price: isassemble == 1 ? res.data[0].assemblePrice : (res.data[0].specVIPprice ? res.data[0].specVIPprice : res.data[0].specPrice),
            price: price
          });
        }
      }
    });
    /** 非 拼团 */
    if (isassemble == 0) {
      var t = new Object();
      t = {
        userOpenId: app.globalData.userInfo.openId,
        createOpenId: that.data.partner.openId,
        vipPrice: that.data.detial_activity.activityVIPprice,
        actPrice: that.data.detial_activity.activityPrice
      }
      /** 我的优惠卷 */
      wx.request({
        url: api.mine.useCoupons,
        data: t,
        success: function(res) {
          if (res.statusCode == 200 && res.data.code == 200) {
            var t = res.data.data;
            console.log(res.data.data)
            if (t.length > 0) {
              that.setData({
                vipPric: res.data.data
              });
            } else {
              that.setData({
                vipPric: []
              });
            }
          }
        }
      });
    }
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    });
    setTimeout(
      function() {
        animation.translateY(0).step();
        this.setData({
          animationData: animation.export()
        });
      }.bind(this),
      200
    );
  },
  //隐藏对话框
  hideModal: function() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export()
    });
    setTimeout(
      function() {
        animation.translateY(0).step();
        this.setData({
          animationData: animation.export(),
          showModalStatus: false
        });
      }.bind(this),
      200
    );
  },
  onShowTextare() {
    //显示textare
    this.setData({
      isShowText: false,
      onFacus: true
    });
  },
  onShowText() {
    //显示text
    this.setData({
      isShowText: true,
      onFacus: false
    });
  },
  onRemarkInput(event) {
    //保存输入框填写内容
    var value = event.detail.value;
    this.setData({
      remark: value
    });
  },
  //点击选择类型
  clickPerson: function() {
    var selectPerson = this.data.selectPerson;
    if (selectPerson == true) {
      this.setData({
        selectArea: true,
        selectPerson: false
      });
    } else {
      this.setData({
        selectArea: false,
        selectPerson: true
      });
    }
  },
  //点击切换
  mySelect: function(e) {
    this.setData({
      selectPerson: true,
      selectArea: false
    });
  },
  bindReply: function(e) {
    console.log(e);
    const conId = e.currentTarget.dataset.id;
    this.setData({
      // replyUserName: ,
      reply: true,
      popup1: false,
      conId: conId
    });
  },
  cancleReply: function() {
    this.setData({
      // replyUserName: ,
      reply: false,
      popup1: true,
      conId: ''
    });
  },
  /* 隐藏弹窗 */
  hidePopup(flag = true) {
    console.log(flag);
    this.setData({
      popup: flag
    });
    // console.log(this.data)
  },
  hidePopup1() {
    this.setData({
      assible: true
    });
    clearTimeout(app.globalData.time);
  },
  modalinput: function() {
    this.hidePopup(false);
  },
  //查看活动的状态
  gotailStatus(e) {
    var that = this;
    const status = e.currentTarget.dataset.status;
    // console.log(status)
    if (status != 4) {
      return;
    } else {
      wx.navigateTo({
        url: "../assemble/assemble?actUUID=" + that.data.detial_activity.activityUUID
      });
    }

  },
  //添加回复
  submitForm1(e) {
    console.log(e)
    var form = e.detail.value;
    var that = this;
    var t = new Object();
    let comment = form.comment;
    if (comment == "") {
      wx.showToast({
        title: "内容为空"
      });
      return false;
    }
    (t.conId = that.data.conId),
    (t.repArea = comment),
    wx.request({
      url: api.detail.addReply,
      data: t,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res);
        if (res.statusCode == 200 && res.data.code == 200) {
          wx.showToast({
            title: "回复成功"
          });
          that.getConsultData();
          that.setData({
            popup: true
          });

        } else {
          wx.showToast({
            title: res.data.msg
          });
        }
      }
    });
  },
  //输出评价
  delReplay(e) {
    const conId = e.currentTarget.dataset.id;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除当前评论',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var t = new Object();
          t.conId = conId;
          wx.request({
            url: api.detail.delConsult,
            data: t,
            method: "POST",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            success: function(res) {
              if (res.statusCode == 200) {
                if (res.data.code == 200) {
                  r.toast.showToast('删除成功');
                  that.getConsultData();
                  that.setData({
                    popup: true
                  });
                }
              }
            }
          })
        } else if (res.cancle) {
          onsole.log('用户点击取消');
        }

      }

    })
  },
  /** 选择优惠卷 */
  selectVip(e) {
    const that = this;
    const coupon = e.currentTarget.dataset.price;
    if (that.data.mcId == coupon.mcId) {
      that.setData({
        selectArea: false,
        selectPerson: true,
      })
      return;
    }
    /** 实付价格 */
    var onlyPrice = (Number(that.data.gg_price) - Number(coupon.price)).toFixed(2);
    that.setData({
      //saveMoney: coupon.price,
      saveMoney: coupon.title,
      selectArea: false,
      selectPerson: true,
      price: onlyPrice,
      mcId: coupon.mcId
    })
  },
  /** 参与拼单 */
  assemble() {
    clearTimeout(app.globalData.time);
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: true,
      assible: true,
      /** 拼团价格 */
      price: this.data.detial_activity.assemble.asPrice,
      isAssemble: 1,
    });
    setTimeout(
      function() {
        animation.translateY(0).step();
        this.setData({
          animationData: animation.export()
        });
      }.bind(this),
      200
    );
  },
  timeFormat(param) { //小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown: function() { //倒计时函数
    var obj = null;
    app.globalData.time = setTimeout(() => {
      // 获取当前时间，同时得到活动结束时间数组
      let newTime = new Date().getTime();
      let endTimeList = this.data.detial_activity.assemble.endTime.replace(/\-/g, "/");

      // 对结束时间进行处理渲染到页面
      // endTimeList.forEach(o => {
      let endTime = new Date(endTimeList).getTime();
      let timeMax = Number(endTime) - Number(newTime);
      // console.log(timeMax)
      // 如果活动未结束，对时间进行处理
      if (timeMax > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
        r.countDown();
      } else { //活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      // console.log(obj)
      // 渲染，然后每隔一秒执行一次倒计时函数
      this.setData({
        time: obj
      })
    }, 1000);
  },

  /** ------------------------------   收藏     ------------------------------ */
  addCollection: function(e) {
    var that = this;
    var res = that.is_authorize();
    if (res == 0) return

    console.log(e)
    const opeType = e.currentTarget.dataset.collection;
    const json = that.data.detial_activity;
    const n = {
      openId: getApp().globalData.wxUserInfo.openId,
      otherId: json.activityId,
      type: 0,
      opeType: opeType
    };
    if (opeType == 0) {
      n.img = json.activityImage;
      n.title = json.activityTitle;
    }
    wx.request({
      url: api.detail.add_del_Collection,
      data: n,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            const tips = opeType == 0 ? '已收藏' : '已取消';
            r.setData({
              isCollection: opeType == 0 ? 1 : 0
            })
            r.toast.showToast(tips);
          }

        }
      }
    });
  },
  map: function(e) {
    const mapdata = e.currentTarget.dataset;
    if (mapdata.lng && mapdata.lat) {
      wx.openLocation({
        latitude: Number(mapdata.lat),
        longitude: Number(mapdata.lng),
        scale: 15,
        name: mapdata.name,
        address: mapdata.address
      })

    }
  },
  /** 是否已授权 */
  is_authorize: function() {
    var openid = getApp().globalData.wxUserInfo.openId;
    console.log('openid -------------> ' + openid)
    if (openid == undefined || openid == '') {
      wx.showToast({
        title: "请先授权，2秒后自动跳转到授权页面",
        icon: "none"
      });
      setTimeout(function() {
        wx.setStorageSync('act_id', act_id);
        wx.navigateTo({
          url: '/pages/welcome/welcome?act_id=' + act_id,
        })
      }, 2000)
      return 0
    } else {
      return 1;
    }
  }

});